﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace T02TcpClient
{
    class TcpClient
    {
        static void Main(string[] args)
        {
            //嵌套字
            Socket client;
            //数据缓冲池
            byte[] buf = new byte[1024];
            //输入数据
            string input;

            //1.建立嵌套字信息
            //获取远程服务器ip地址
            IPAddress remote = IPAddress.Parse("127.0.0.1");
            //段口号实际范围1~65535,其中1~1024为系统保留，也需注意避开约定俗成的常见端口
            IPEndPoint iep = new IPEndPoint(remote, 13000);
            //2.发送请求连接，服务器想用会拒绝或网络出现故障
            try
            {
                //建立ipv4流方式 Tcp协议 嵌套字
                client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,
                    ProtocolType.Tcp);
                client.Connect(iep);    
            }catch (SocketException e)
            {
                Console.WriteLine("无法连接到服务器");
                    return;
            }
            //3.数据交换
            while (true)
            {
                input = Console.ReadLine();
                if (input=="exit")
                {
                    break;
                }
                client.Send(Encoding.ASCII.GetBytes(input));
                //接收应答
                int rec = client.Receive(buf);
                Console.WriteLine(Encoding.ASCII.GetString(buf, 0, rec));
            }
            //释放资源
            Console.WriteLine("断开连接");
            client.Close();
        }
    }
}